﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Serialization;
using Barbar.MapReport.DataSource.Entities;
using Barbar.MapReport.DataSource.Resources;
using System.IO;
using System.Web;

namespace Barbar.MapReport.DataSource {
  public class RegionProviderFile : RegionProvider {
    private string m_Path;
 
    public override void Initialize(string name, NameValueCollection config) {
      base.Initialize(name, config);

      if (config == null)
        throw new ArgumentNullException("config");

      m_Path = config["path"];
      if (String.IsNullOrEmpty(m_Path))
        throw new DataSourceException(Translator.Error_PathNotSpecified);

      if (HttpContext.Current != null && m_Path.StartsWith("~", StringComparison.Ordinal)) {
        m_Path = HttpContext.Current.Server.MapPath(m_Path);
      }

      if (!File.Exists(m_Path))
        throw new DataSourceException(Translator.Error_FileNotFound);
    }

    public override IEnumerable<IRawRegion> Regions {
      get {
        using (XmlReader reader = XmlReader.Create(m_Path)) {
          XmlSerializer serializer = new XmlSerializer(typeof(RawRegionCollection), Constants.DataSourceXmlNamespace);
          RawRegionCollection result = (RawRegionCollection)serializer.Deserialize(reader);
          foreach (RawRegion region in result)
            yield return region;
        }
      }
    }
  }
}
